package org.raymond.icloud.common.starter.webFilter;

import lombok.extern.slf4j.Slf4j;
import org.raymond.icloud.common.core.util.http.CachedRequestWrapper;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class DataReusableFilter extends AbstractFilter {
    @Override
    protected void doFilterSub(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        CachedRequestWrapper cachedRequestWrapper = new CachedRequestWrapper(request);
        ContentCachingRequestWrapper cachingRequestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper cachingResponseWrapper = new ContentCachingResponseWrapper(response);

        try {
            filterChain.doFilter(cachedRequestWrapper, cachingResponseWrapper);

            cachingResponseWrapper.setHeader("Access-Control-Allow-Origin", "*");
            /*
            cachingResponseWrapper.setHeader("Access-Control-Allow-Methods", "*");
            cachingResponseWrapper.setHeader("Access-Control-Allow-Headers", "*");
            cachingResponseWrapper.setHeader("Access-Control-Max-Age", "3600");
             */
        } finally {
            cachingResponseWrapper.copyBodyToResponse();
        }
    }
}
